﻿using Learun.Application.Base.SystemModule;
using Learun.Application.Organization;
using Learun.Util;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using static Learun.Util.SqlSugar.SqlSugarHelper;

namespace Learun.Application.TwoDevelopment.ZZDT_EC
{
    /// <summary>
    /// 版 本 PIT-ADMS V7.0.3 敏捷开发框架
    /// Copyright (c) 2013-2018 Hexagon PPM
    /// 创 建：超级管理员
    /// 日 期：2022-04-11 09:45
    /// 描 述：项目备份表
    /// </summary>
    public class ec_project_bakupBLL : ec_project_bakupIBLL
    {
        private ec_project_bakupService ec_project_bakupService = new ec_project_bakupService();

        #region 获取数据
        /// <summary>
        /// 获取页面显示列表数据
        /// <summary>
        /// <param name="queryJson">查询参数</param>
        /// <returns></returns>
        public IEnumerable<ec_project_bakupEntity> GetList(string queryJson, Pagination pagination = null)
        {
            try
            {
                var queryParam = queryJson.ToJObject();
                var ProjectId = queryParam["ProjectId"]?.ToString();
                var BakupName = queryParam["BakupName"]?.ToString();

                var query = Db.Queryable<ec_project_bakupEntity>()
                    .WhereIF(!string.IsNullOrEmpty(ProjectId), x => x.ProjectId == ProjectId)
                    .WhereIF(!string.IsNullOrEmpty(BakupName), x => x.BakupName.Contains(BakupName))
                    .OrderByDescending(x => x.CreateTime);
                List<ec_project_bakupEntity> list;
                if (pagination == null)
                {
                    list = query.ToList();
                }
                else
                {
                    list = query.ToPageList(pagination.page, pagination.rows);
                }
                var users = Db.Queryable<UserEntity>().ToList();
                list?.ForEach(x =>
                {
                    x.CreateUserName = users.FirstOrDefault(y => y.F_UserId == x.CreateUserID)?.F_RealName;
                });
                return list;
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex);
                }
            }
        }

        /// <summary>
        /// 获取实体数据
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        public ec_project_bakupEntity GetEntity(string keyValue)
        {
            try
            {
                return ec_project_bakupService.GetEntity(keyValue);
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex);
                }
            }
        }

        #endregion

        #region 提交数据

        /// <summary>
        /// 删除实体数据
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        public void DeleteEntity(string keyValue)
        {
            try
            {
                ec_project_bakupService.DeleteEntity(keyValue);
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex);
                }
            }
        }

        /// <summary>
        /// 保存实体数据（新增、修改）
        /// <summary>
        /// <returns></returns>
        public void SaveEntity(string projectId, string projectName, string ZipFilesPath, string currentUserId, string currentUserName, long fileSize)
        {
            try
            {
                //新增备份表数据
                ec_project_bakupEntity projectBakupEntity = new ec_project_bakupEntity();
                projectBakupEntity.ProjectBakupID = Guid.NewGuid().ToString();
                projectBakupEntity.ProjectId = projectId;
                projectBakupEntity.BakupName = projectName + "_备份_" + DateTime.Now.ToString("yyyyMMddHHmmss");
                projectBakupEntity.FolderId = Guid.NewGuid().ToString();
                projectBakupEntity.CreateTime = Time.MySqlTime;
                projectBakupEntity.CreateUserID = currentUserId;
                //新增附件表数据
                AnnexesFileEntity annexesFiles = new AnnexesFileEntity();
                annexesFiles.F_Id = Guid.NewGuid().ToString();
                annexesFiles.F_FolderId = projectBakupEntity.FolderId;
                annexesFiles.F_CreateDate = Time.MySqlTime;
                annexesFiles.F_FileName = Path.GetFileName(ZipFilesPath);
                annexesFiles.F_FilePath = ZipFilesPath;
                annexesFiles.F_FileSize = fileSize.ToString();
                annexesFiles.F_FileExtensions = ".zip";
                annexesFiles.F_FileType = "zip";
                annexesFiles.F_CreateUserId = currentUserId;
                annexesFiles.F_CreateUserName = currentUserName;
                annexesFiles.F_CreateDate = Time.MySqlTime;
                ec_project_bakupService.SaveEntity(projectBakupEntity, annexesFiles);
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex);
                }
            }
        }

        /// <summary>
        /// 保存实体数据（新增、修改）
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        public void OnlySaveEntity(string keyValue, ec_project_bakupEntity entity)
        {
            try
            {
                ec_project_bakupService.OnlySaveEntity(keyValue, entity);
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex);
                }
            }
        }

        /// <summary>
        /// 往sqlite里面创建或者添加表
        /// <summary>
        /// <returns></returns>
        public void CreateAndAddBySqlit(string ProjectId, List<string> list_tblName, string sqlitePath, string fileBackupPath, string ProjectIndex)
        {
            try
            {
                BaseDAL baseDAL = new BaseDAL();
                List<AnnexesFileEntity> listAnnexesFile = new List<AnnexesFileEntity>();
                List<string> listFolderId = new List<string>();
                string queryJson = "{ProjectId:\"" + ProjectId + "\"}";
                foreach (var table in list_tblName)
                {
                    listFolderId = new List<string>();
                    if (table == "ec_enginedata_property")
                    {
                        //创建工程数据属性表
                        baseDAL.Create<ec_enginedata_propertyEntity>(sqlitePath);
                        //添加工程数据属性表数据
                        baseDAL.Add(new ec_enginedata_propertyService().GetTagPropById(ProjectId, "").ToList(), sqlitePath);
                        continue;
                    }
                    if (table == "ec_enginedata_pixel")
                    {
                        //创建工程数据图元表
                        baseDAL.Create<ec_enginedata_pixelEntity>(sqlitePath);
                        //添加工程数据图元表数据
                        baseDAL.Add(new ec_enginedata_pixelService().GetList(queryJson).ToList(), sqlitePath);
                        continue;
                    }
                    if (table == "ec_enginedata")
                    {
                        //创建工程数据表
                        baseDAL.Create<ec_enginedataEntity>(sqlitePath);
                        //添加工程数据表数据
                        baseDAL.Add(new ec_enginedataBLL().GetList(queryJson).ToList(), sqlitePath);
                        continue;
                    }
                    if (table == "ec_objecttypelib")
                    {
                        //创建对象类型元件库表
                        baseDAL.Create<ec_objecttypelibEntity>(sqlitePath);
                        //添加对象类型元件库表数据
                        baseDAL.Add(new ec_objecttypelibService().GetObjectTypeLib("", ProjectId).ToList(), sqlitePath);
                        continue;
                    }
                    if (table == "ec_objecttype")
                    {
                        //创建对象类型表
                        baseDAL.Create<ec_objecttypeEntity>(sqlitePath);
                        //添加对象类型表数据
                        baseDAL.Add(new ec_objecttypeBLL().GetList(queryJson).ToList(), sqlitePath);
                        continue;
                    }
                    if (table == "ec_objecttypep")
                    {
                        //创建对象类型属性表
                        baseDAL.Create<ec_objecttypepEntity>(sqlitePath);
                        //添加对象类型属性表数据
                        baseDAL.Add(new ec_objecttypepService().GetObjectTypePById("", ProjectId).ToList(), sqlitePath);
                        continue;
                    }
                    if (table == "ec_property")
                    {
                        //创建属性表
                        baseDAL.Create<ec_propertyEntity>(sqlitePath);
                        //添加属性表数据
                        baseDAL.Add(new ec_propertyBLL().GetList(queryJson).ToList(), sqlitePath);
                        continue;
                    }
                    if (table == "ec_propertyg")
                    {
                        //创建属性组表
                        baseDAL.Create<ec_propertygEntity>(sqlitePath);
                        //添加属性组表数据
                        baseDAL.Add(new ec_propertygBLL().GetList(queryJson).ToList(), sqlitePath);
                        continue;
                    }
                    if (table == "ec_operate_log")
                    {
                        //创建操作日志表
                        baseDAL.Create<ec_operate_logEntity>(sqlitePath);
                        //添加操作日志表数据
                        baseDAL.Add(new ec_operate_logBLL().GetList(queryJson).ToList(), sqlitePath);
                        continue;
                    }
                    if (table == "ec_drawing_publish")
                    {
                        //创建图纸发布表
                        baseDAL.Create<ec_drawing_publishEntity>(sqlitePath);
                        //添加图纸发布表数据
                        baseDAL.Add(new ec_drawing_publishBLL().GetList(queryJson).ToList(), sqlitePath);
                        continue;
                    }
                    if (table == "ec_drawing_syn")
                    {
                        //创建图纸同步表
                        baseDAL.Create<ec_drawing_synEntity>(sqlitePath);
                        //添加图纸同步表数据
                        baseDAL.Add(new ec_drawing_synBLL().GetList(queryJson).ToList(), sqlitePath);
                        continue;
                    }
                    if (table == "ec_drawing_file")
                    {
                        //创建图纸文件表
                        baseDAL.Create<ec_drawing_fileEntity>(sqlitePath);
                        var drawingData = new ec_drawing_fileBLL().GetList(queryJson).ToList();
                        if (drawingData != null && drawingData.Count > 0)
                        {
                            listFolderId = drawingData.Select(x => x.FolderId).ToList();
                            listAnnexesFile.AddRange(GetProjectAnnexesFile(listFolderId, fileBackupPath));
                        }
                        //添加图纸文件表数据
                        baseDAL.Add(drawingData, sqlitePath);
                        continue;
                    }
                    if (table == "ec_drawing_catalogue")
                    {
                        //创建图纸目录表
                        baseDAL.Create<ec_drawing_catalogueEntity>(sqlitePath);
                        //添加图纸目录表数据
                        baseDAL.Add(new ec_drawing_catalogueService().GetList(queryJson).ToList(), sqlitePath);
                        continue;
                    }
                    if (table == "ec_library_file")
                    {
                        //创建元件库文件表
                        baseDAL.Create<ec_library_fileEntity>(sqlitePath);
                        var libraryFileData = new ec_library_fileBLL().GetList(queryJson).ToList();
                        if (libraryFileData != null && libraryFileData.Count > 0)
                        {
                            listFolderId = libraryFileData.Select(x => x.FolderId).ToList();
                            listAnnexesFile.AddRange(GetProjectAnnexesFile(listFolderId, fileBackupPath));
                        }
                        //添加元件库文件表数据
                        baseDAL.Add(libraryFileData, sqlitePath);
                        continue;
                    }
                    if (table == "ec_library_catalogue")
                    {
                        //创建元件库目录表
                        baseDAL.Create<ec_library_catalogueEntity>(sqlitePath);
                        //添加元件库目录表数据
                        baseDAL.Add(new ec_library_catalogueService().GetList(queryJson).ToList(), sqlitePath);
                        continue;
                    }
                    if (table == "ec_template_file")
                    {
                        //创建样板文件表
                        baseDAL.Create<ec_template_fileEntity>(sqlitePath);
                        var templateData = new ec_template_fileBLL().GetList(queryJson).ToList();
                        if (templateData != null && templateData.Count > 0)
                        {
                            listFolderId = templateData.Select(x => x.FolderId).ToList();
                            listAnnexesFile.AddRange(GetProjectAnnexesFile(listFolderId, fileBackupPath));
                        }
                        //添加样板文件表数据
                        baseDAL.Add(templateData, sqlitePath);
                        continue;
                    }
                    if (table == "ec_template_catalogue")
                    {
                        //创建样板目录表
                        baseDAL.Create<ec_template_catalogueEntity>(sqlitePath);
                        //添加样板目录表数据
                        baseDAL.Add(new ec_template_catalogueBLL().GetList(queryJson).ToList(), sqlitePath);
                        continue;
                    }
                    if (table == "ec_dataitem")
                    {
                        //创建字典分类表
                        baseDAL.Create<ec_dataitemEntity>(sqlitePath);
                        //添加字典分类表数据
                        baseDAL.Add(new ec_dataitemBLL().GetList(queryJson, false).ToList(), sqlitePath);
                        continue;
                    }
                    if (table == "ec_dataitemdetail")
                    {
                        //创建字典明细表
                        baseDAL.Create<ec_dataitemdetailEntity>(sqlitePath);
                        //添加字典明细表数据
                        baseDAL.Add(new ec_dataitemService().GetDetailList(null, null, ProjectId, true).ToList(), sqlitePath);
                        continue;
                    }
                    if (table == "ec_report_catalogue")
                    {
                        //创建报表目录表
                        baseDAL.Create<ec_report_catalogueEntity>(sqlitePath);
                        //添加报表目录表数据
                        baseDAL.Add(new ec_report_catalogueBLL().GetList(queryJson).ToList(), sqlitePath);
                        continue;
                    }
                    if (table == "ec_report_file")
                    {
                        //创建报表文件表
                        baseDAL.Create<ec_report_fileEntity>(sqlitePath);
                        var reportFileData = new ec_report_fileBLL().GetList(queryJson).ToList();
                        if (reportFileData != null && reportFileData.Count > 0)
                        {
                            listFolderId = reportFileData.Select(x => x.FolderId).ToList();
                            listAnnexesFile.AddRange(GetProjectAnnexesFile(listFolderId, fileBackupPath));
                        }
                        //添加报表文件表数据
                        baseDAL.Add(reportFileData, sqlitePath);
                        continue;
                    }
                    if (table == "ec_enginedata_propertyhis")
                    {
                        //创建工程数据属性历史表
                        baseDAL.Create<ec_enginedata_propertyhisEntity>(sqlitePath);
                        //添加工程数据属性历史表数据
                        baseDAL.Add(new ec_enginedata_propertyhisBLL().GetList(queryJson).ToList(), sqlitePath);
                        continue;
                    }
                    if (table == "ec_reltype")
                    {
                        //创建关联类型表
                        baseDAL.Create<ec_reltypeEntity>(sqlitePath);
                        //添加关联类型表数据
                        baseDAL.Add(new ec_reltypeBLL().GetList(queryJson).ToList(), sqlitePath);
                        continue;
                    }
                    if (table == "ec_enginedata_rel")
                    {
                        //创建工程数据关联表
                        baseDAL.Create<ec_enginedata_relEntity>(sqlitePath);
                        //添加工程数据关联表数据
                        baseDAL.Add(new ec_enginedata_relBLL().GetList(queryJson).ToList(), sqlitePath);
                        continue;
                    }
                    if (table == "ec_measuring_unit")
                    {
                        //创建计量单位表
                        baseDAL.Create<ec_measuring_unitEntity>(sqlitePath);
                        //添加计量单位表数据
                        baseDAL.Add(new ec_measuring_unitBLL().GetList(queryJson).ToList(), sqlitePath);
                        continue;
                    }
                    if (table == "ec_measuring_unittype")
                    {
                        //创建计量单位分类表
                        baseDAL.Create<ec_measuring_unittypeEntity>(sqlitePath);
                        //添加计量单位分类表数据
                        baseDAL.Add(new ec_measuring_unittypeBLL().GetList(queryJson).ToList(), sqlitePath);
                        continue;
                    }
                    if (table == "lr_base_annexesfile")
                    {
                        //创建附件表
                        baseDAL.Create<AnnexesFileEntity>(sqlitePath);
                        //添加附件表数据
                        baseDAL.Add(listAnnexesFile, sqlitePath);
                        continue;
                    }
                }
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex);
                }
            }
        }

        public List<AnnexesFileEntity> GetProjectAnnexesFile(List<string> listFolderId, string fileBackupPath)
        {
            List<AnnexesFileEntity> listAnnexesFile = new List<AnnexesFileEntity>();
            foreach (var item in listFolderId)
            {
                var fileList = new AnnexesFileService().GetList(item).ToList();
                for (var i = 0; i < fileList.Count; i++)
                {
                    listAnnexesFile.Add(fileList[i]);
                    if (File.Exists(fileList[i].F_FilePath))
                    {
                        File.Copy(fileList[i].F_FilePath, Path.Combine(fileBackupPath, fileList[i].F_Id + fileList[i].F_FileExtensions));
                    }
                }
            }
            return listAnnexesFile;
        }

        /// <summary>
        /// 获取sqlite里面的数据还原到数据库
        /// </summary>
        /// <param name="list_tblName">要还原的业务表名</param>
        /// <param name="sqlitePath">sqlite数据库</param>
        /// <param name="fileBackupPath">附件路劲</param>
        /// <param name="ProjectIndex">项目序号</param>
        public void RestoreBySqlite(List<string> list_tblName, string sqlitePath, string fileBackupPath, string ProjectIndex)
        {
            try
            {
                ec_project_bakupService.RestoreBySqlite(list_tblName, sqlitePath, fileBackupPath, ProjectIndex);
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex);
                }
            }
        }
        #endregion


    }
}
